//
//  PersonalViewController.m
//  ShareNavigation
//
//  Created by 水木 傅 on 12-5-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "PersonalViewController.h"
#import "SingletonUser.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "UIImageCategory.h"

@implementation PersonalViewController
@synthesize HeadPhoto;
@synthesize userID;
@synthesize imageName;
@synthesize PressButton;



//---  异步回调的函数  ---

-(void) requestRegisterFinished :(ASIHTTPRequest *)request
{
    NSString *response = request.responseString;
    NSLog(@"%@",response);
    if([response isEqualToString:@"FALSE"])
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"警告"
                 message:@"连接服务器错误"
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:@"重新查看行程",nil];
        [alert show];
        
    }
    else if([response isEqualToString:@"NULL"])
    {
        self.HeadPhoto.image = [UIImage imageNamed:@"null.jpg"];
    }
    else
    {
        self.HeadPhoto.image = [self RequesHeadPhoto:response];
    }
}

-(void) requestRegisterFailed :(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
}



//---  获取数据  ---
-(void) getData:(NSString *) UserId
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/ModifyPersonal.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:UserId forKey:@"UserID"];
    [request setPostValue:@"TRUE" forKey:@"isRequest"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestRegisterFinished:)];
    [request setDidFailSelector:@selector(requestRegisterFailed:)];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //---  发送请求信息  ----
    [request startAsynchronous];
}
//---  下载图片  ----
-(UIImage *) RequesHeadPhoto:(NSString *)image
{
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/upload/%@.jpg",image];
    NSURL *url  =[NSURL URLWithString: urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                             NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
        
    NSString *archivePath = [documentsDirectory 
                                 stringByAppendingPathComponent:
                                 [NSString stringWithFormat:@"%@.jpg",image]];
      
    [request setDownloadDestinationPath:archivePath];
    return [UIImage imageWithContentsOfFile:archivePath];
}


#pragma 图片选择的委托
//---  从图片库中选择图片  ---
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
 //   UIImage *image =  [[self requestImage:sign.UUID] transformWidth:81 height:81];
    UIImage *changedImage =[image transformWidth:82 height:82];
    NSData *imageData = UIImagePNGRepresentation(changedImage);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //---  设置图片在本应用程序中的位置  ---
    NSString *archivePath = [documentsDirectory 
                             stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"%@.jpg",imageName]];
    [imageData writeToFile:archivePath  atomically:YES];
    self.HeadPhoto.image = changedImage;
    self.PressButton.enabled = TRUE;
    [self dismissModalViewControllerAnimated:YES];
}

//---  加载窗体  ---
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.userID.text = [SingletonUser shareManager].UserID;
    //---  加载图片数据  ---
    [self getData:self.userID.text];
    
}

- (void)viewDidUnload {
    [self setHeadPhoto:nil];
    [self setUserID:nil];
    [self setPressButton:nil];
    [super viewDidUnload];
}

//生成随即的uuid
- (NSString*) stringWithUUID {
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    //get the string representation of the UUID
    NSString    *uuidString =(__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    return uuidString;
}

//---  界面按钮的响应函数  ---
//---  图片库获取图片  ---
- (IBAction)uploadImage:(id)sender {
    self.imageName = [self stringWithUUID];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) 
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"访问图片库出错" message:@"设备不支持图片库访问" delegate:nil cancelButtonTitle:@"返回!" otherButtonTitles:nil];
        [alert show];
    }
}
//---  确定修改  ---
- (IBAction)modify:(id)sender 
{
    [self upload:self.imageName];
}


-(void) upload:(NSString *)imageName
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/ModifyPersonal.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request setPostValue:self.imageName forKey:@"HeadPhoto"];
    [request setPostValue:self.userID.text forKey:@"UserID"];
    [request setPostValue:@"FALSE" forKey:@"isRequest"];
    //---  获取图片数据  ---
    NSData *imageData = UIImagePNGRepresentation(self.HeadPhoto.image);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //---  设置图片在本应用程序中的位置  ---
    NSString *archivePath = [documentsDirectory 
                             stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"%@.jpg",self.imageName]];
    [request addData:imageData withFileName:archivePath andContentType:@"image/jpg" 
              forKey:@"image"];
    [request startSynchronous];
    if([request.responseString isEqualToString:@"TRUE"])
    {
        self.PressButton.enabled = FALSE;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"上传成功" delegate:nil cancelButtonTitle:@"返回" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"上传失败" delegate:nil cancelButtonTitle:@"返回" otherButtonTitles:@"重新上传",nil];
        alert.tag = 1;
        [alert show];
    }
}

#pragma   ---  弹出框委托  ---
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) 
    {
        if(buttonIndex == 1)
        {
            [self upload:self.imageName];
        }
    }
}

@end
